package me.youline.dataServer.service.authentication;

import me.youline.dataServer.dao.authentication.UserCredentialInfoDAO;
import me.youline.dataServer.entity.UserCredentialInfo;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SaltedAuthenticationInfo;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class UsernamePasswordRealm extends AuthorizingRealm {

	@Autowired
	private UserCredentialInfoDAO credentialDAO;

	private final static String REALM_NAME = "youlime_usernamePassword";

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		UserCredentialInfo credential = credentialDAO.findByUserName(token
				.getPrincipal().toString());
		SaltedAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo( 
				credential.getUserId(), credential.getHash(),
				ByteSource.Util.bytes(credential.getSalt()), REALM_NAME);
		return authenticationInfo;
	}

	@Override
	public String getName() {
		return REALM_NAME;
	}

	@Override
	public boolean supports(AuthenticationToken token) {
		return token instanceof UsernamePasswordToken;
	}

}
